package com.comp3111.happymeal;

import com.comp3111.happymeal.NavigationDrawerActivity;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;

import com.configuration.Configuration;
import com.controller.RestaurantCommentFetch;
import com.controller.RestaurantFetch;
import com.object.Restaurant;

public class RestaurantListActivity extends NavigationDrawerActivity{
		
		//Back button
		private int backButtonCount;
		
		private ListView restaurantListView;
	    private SimpleAdapter adapter;
	    private List<Integer> restaurantIdList;	// Store the mealId into a list to allow getting the mealId of meal in restaurantListView of certain position
	    
	    //for creating picture
	    Drawable drawableTmp;
	    String drawableURL;
	    
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.page_using_listview_only);
	        createDrawer();
	        
	        //Initialize the backButtonCount
	        backButtonCount = 0;
	        
	        //restaurant_list contains many restaurant_list_item
	        restaurantListView = (ListView)findViewById(R.id.page_using_listview_only_listview);
	        adapter = new SimpleAdapter(this, getDataRestaurantListview(), R.layout.restaurant_list_item,
					new String[]{"restaurant_list_item_picture","restaurant_list_item_name","restaurant_list_item_address"},
					new int[]{R.id.restaurant_list_item_picture, R.id.restaurant_list_item_name, R.id.restaurant_list_item_address});
	        restaurantListView.setAdapter(adapter);
	        
	        //For display for picture
	        adapter.setViewBinder(new ViewBinder(){
	        	public boolean setViewValue(View view,Object data,String textRepresentation){
					if(view instanceof ImageView && data instanceof Drawable){
						ImageView iv=(ImageView)view;
						iv.setImageDrawable((Drawable)data);
						return true;
					}
					else return false;
				}
	        });
	        
	        restaurantListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	            @Override
	            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
	                // TODO Auto-generated method stub
	            	int restaurantId = restaurantIdList.get(position);
	                //Toast.makeText(RestaurantListActivity.this,"ID" + Integer.toString(mealId) ,Toast.LENGTH_SHORT).show();
	                
	                //Jump to FoodFoodPageActivity
	                Intent intentPass = new Intent(RestaurantListActivity.this, RestaurantPageActivity.class);
					
					//Pass pass intent								
					intentPass.putExtra("RESTAURANTID",Integer.toString(restaurantId).trim());
						
					//Go to next page
					startActivity(intentPass);
	            }
	        });
	        
	        //Release unused ram
	        System.gc();
	        
	    }
	    
	    private List<Map<String, Object>> getDataRestaurantListview() {
	    	
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			
			restaurantIdList = new ArrayList<Integer>();
			
			RestaurantFetch restaurantFetch = new RestaurantFetch();
			List<Restaurant> restaurantList = restaurantFetch.fetchAllRestaurant();
			
		    if(restaurantList != null){
			    for(Restaurant restaurant:restaurantList){
					Map<String, Object> map = new HashMap<String, Object>();
					
					drawableURL = Configuration.baseURL + restaurant.getProfilePicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  
							drawableTmp = loadImageFromURL(drawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
					
					RestaurantCommentFetch restaurantCommentFetch = new RestaurantCommentFetch();
					
					map.put("restaurant_list_item_picture", drawableTmp);
					//map.put("restaurant_list_item_picture", R.drawable.food_banner);
					map.put("restaurant_list_item_name", restaurant.getName());
					map.put("restaurant_list_item_address", restaurant.getAddress());
					map.put("restaurant_list_item_rating", Float.toString(restaurantCommentFetch.fetchRestaurantRating(restaurant.getId())));
					list.add(map);
					
					//List containing restaurant id in order
					restaurantIdList.add(restaurant.getId());
					
					
					
		    	}
		    }
		    
			return list;
		}
	    
	    //the app will not allow it to go back to previous Activity through back
	  	// Override the back button to quit the app if back is pressed twice
	    public void onBackPressed(){
			if(Configuration.showLog){
				Log.d("RestaurantListActivity", "onBackPressed");
			}
				
	        if(backButtonCount >= 1){
	            Intent intent = new Intent(Intent.ACTION_MAIN);
	            intent.addCategory(Intent.CATEGORY_HOME);
	            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            startActivity(intent);
	        }else{
	            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
	            backButtonCount++;
	        }
		}
	    
	    private Drawable loadImageFromURL(String url){
	        try{
	        	InputStream is = (InputStream) new URL(url).getContent();
	            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
	            return new BitmapDrawable(getResources(), tmp);
	            /*
	            InputStream is = (InputStream) new URL(url).getContent();
	            Drawable draw = Drawable.createFromStream(is, "src");
	            return draw;*/
	        }catch (Exception e) {
	            //TODO handle error
	            Log.i("loadingImg", e.toString());
	            return null;
	        }
	    }

}
